package com.zadtek.sharkRider.activity;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.zadtek.sharkRider.R;
import com.zadtek.sharkRider.activity.common.Common;
import com.zadtek.sharkRider.activity.common.Const;
import com.zadtek.sharkRider.activity.data.OrderOverData;
import com.zadtek.sharkRider.activity.data.SygOrdOverData;
import com.zadtek.sharkRider.frame.JsonProcessHelper;
import com.zadtek.sharkRider.views.PullDownView;
import com.zadtek.sharkRider.views.PullDownView.OnPullDownListener;

/**
 * 随意购-已完成订单列表
 * @author kuyukeji
 *
 */
public class SygOrderOverActivity extends BaseActivity {
	
	private ImageView backid;
	private TextView topview;
	
	private TextView ordernum;	//累计单量
	
	private PullDownView pulldownview;
	private ListView listView; 
	private OrderOverData overData;
	private OrderOverData refoverData;
	
	private ArrayList<SygOrdOverData> sygordlist;
	private ListAdapter listAdapter;
	
	private LayoutInflater inflater;
	
	private int refs = 1; // 页码
	private int pagecount = 0; // 总页数
	
	private SharedPreferences sp; // 用户信息缓存
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sygorder_over);
		
		inflater = getLayoutInflater();
		backid = (ImageView) findViewById(R.id.backid);
		topview = (TextView) findViewById(R.id.topview);
		topview.setText("已完成的跑腿任务");
		backid.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
		ordernum = (TextView) findViewById(R.id.ordernum);
		
		pulldownview = (PullDownView) findViewById(R.id.pulldownview);
		pulldownview.enableAutoFetchMore(true, 0);
		
		listView = pulldownview.getListView();
		listAdapter = new ListAdapter();
//		listView.setDividerHeight(20);
		listView.setAdapter(listAdapter);
		
		//加载数据
		initArrays(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (!"emp".equals(msg.obj.toString())) {
					overData = (OrderOverData) msg.obj;
					ordernum.setText(overData.getTotal()+"单");
					sygordlist = overData.getSygordlist();
					listAdapter.notifyDataSetChanged();
					pulldownview.notifyDidDataLoad(false);
					// 计算出总页数
					int count = Integer.parseInt(overData.getTotal());
					int pagenum = Integer.parseInt(overData.getNumber());
					pagecount = count / pagenum
							+ (count % pagenum > 0 ? 1 : 0);
					if (pagecount <= 1) {
						pulldownview.notifyDidLoadMore(true);
					}
				} else {
					pulldownview.notifyDidDataLoad(false);
					if (overData == null) {
						Common.DisplayToast(SygOrderOverActivity.this, "通信失败,请检查网络!",
								1);
					} else {
						Common.DisplayToast(SygOrderOverActivity.this,
								overData.getMessage(), 2);
					}
				}
			}
		});
		
		pulldownview.setOnPullDownListener(new OnPullDownListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				// 刷新
				if (Common.isNetworkConnected(SygOrderOverActivity.this)) {
					initArrays(new Handler() {
						@Override
						public void handleMessage(Message msg) {
							if (!"emp".equals(msg.obj.toString())) {
								refs = 1;// 刷新后，当前页重置为1
								overData = (OrderOverData) msg.obj;
								ordernum.setText(overData.getTotal()+"单");
								sygordlist = overData.getSygordlist();
								listAdapter.notifyDataSetChanged();
								pulldownview.notifyDidRefresh(true);
							} else {
//								Common.DisplayToast(SygOrderOverActivity.this,
//										"通信失败,请检查网络!", 1);
								pulldownview.notifyDidRefresh(true);
							}
							if (pagecount <= refs) {
								pulldownview.notifyDidLoadMore(true);
							} else {
								pulldownview.notifyDidLoadMore(false);
							}
						}
					});
				} else {
					Common.DisplayToast(SygOrderOverActivity.this, "通信失败,请检查网络!",
							1);
					pulldownview.notifyDidRefresh(true);
				}
			}

			@Override
			public void onLoadMore() {
				// TODO Auto-generated method stub
				// new ForumPostAsyncTask().execute("onLoadMore");
				getNewString(new Handler() {
					@Override
					public void handleMessage(Message msg) {
						if (!"emp".equals(msg.obj.toString())) {

							ArrayList<SygOrdOverData> overlist = refoverData.getSygordlist();
							int size = overlist!=null? overlist.size():0;
							for (int i = 0; i < size; i++) {
								sygordlist.add((SygOrdOverData) overlist.get(i));
							}
							listAdapter.notifyDataSetChanged();
						} else {
							if (refoverData == null) { // 网络失败
								Common.DisplayToast(SygOrderOverActivity.this,
										"通信失败,请检查网络!", 1);
							} else {
								listAdapter.notifyDataSetChanged();
							}
						}
						if (pagecount <= refs) {
							pulldownview.notifyDidLoadMore(true);
						} else {
							pulldownview.notifyDidLoadMore(false);
						}
					}
				});
			}
		});
		
	}
	
	
	private void initArrays(final Handler handler) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					sp = getSharedPreferences(Const.PREF_NAME,
							Context.MODE_PRIVATE);
					String uid = sp.getString("uid", "");
					OrderOverData datas = JsonProcessHelper
							.jsonProcess_syggetoverOrd("get_overorder_list", uid,
									"1");
					if (datas != null && datas.getStatus().equals("200")) {
						handler.obtainMessage(0, datas).sendToTarget();
					} else {
						handler.obtainMessage(0, "emp").sendToTarget();
					}
				} catch (Exception e) {
					Thread.interrupted();
					e.printStackTrace();
				}

			}
		}).start();
	}
	
	//获取更多新闻列表信息
	private void getNewString(final Handler handler) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(2000);
					refs++;

					int threadcount = 0, pagenum = 0;
					int fy = 0;
					threadcount = Integer.parseInt(overData.getTotal());
					pagenum = Integer.parseInt(overData.getNumber());
					fy = threadcount / pagenum
							+ (threadcount % pagenum > 0 ? 1 : 0);
					pagecount = fy;
					if (fy >= refs) {
						sp = getSharedPreferences(Const.PREF_NAME,
								Context.MODE_PRIVATE);
						String uid = sp.getString("uid", "");
						refoverData = JsonProcessHelper.jsonProcess_syggetoverOrd(
								"get_overorder_list", uid, refs + "");
						if (refoverData != null) {
							handler.obtainMessage(0, refoverData).sendToTarget();
						} else {
							handler.obtainMessage(0, "emp").sendToTarget();
							refs--;
						}
					} else {
						handler.obtainMessage(0, "emp").sendToTarget();
					}
				} catch (Exception e) {
					Thread.interrupted();
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	
	public class ListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return sygordlist != null ? sygordlist.size() : 0;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// TODO Auto-generated method stub
			if (sygordlist != null) {// 判断软键盘是否已使用
				ViewHolder holder = null;
				if (convertView == null) {
					convertView = inflater.inflate(R.layout.sygorder_over_item,
							null);
					holder = new ViewHolder();
					holder.mainord = (TextView) convertView
							.findViewById(R.id.mainord); // 
					holder.psmoney = (TextView) convertView
							.findViewById(R.id.psmoney);
					holder.typename = (TextView) convertView
							.findViewById(R.id.typename); // 
					holder.addtime = (TextView) convertView
							.findViewById(R.id.addtime); // 
					holder.wpname = (TextView) convertView
							.findViewById(R.id.wpname); // 
					holder.sendaddr = (TextView) convertView
							.findViewById(R.id.sendaddr); // 
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
				if (convertView != null && sygordlist.size() > position) {
					final SygOrdOverData overday = sygordlist.get(position);
					
					holder.mainord
							.setText("订单号："+overday.getOrder_id());
					holder.psmoney.setText("合计"+overday.getPercentage()+"元");
					String type = overday.getType();
					if (type.equals("buy")) {// 买
						holder.typename.setText("帮你买");
						
					} else if (type.equals("send")) {// 送
						holder.typename.setText("帮你送");
						
					} else if (type.equals("get")) {
						holder.typename.setText("帮你取");
					}
					holder.addtime.setText(overday.getAddtime());
					holder.wpname.setText(overday.getTitle());
					holder.sendaddr.setText(overday.getAddress() + "  "
							+ overday.getMap_location());
					
					convertView.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							Intent intent = new Intent(SygOrderOverActivity.this,
									SygOrdDetailActivity_.class);
							intent.putExtra("mainid", overday.getOrder_id());
							intent.putExtra("location", "");
							intent.putExtra("location_get", "");
							startActivity(intent);
							
						}
					});
					
				}

			}
			return convertView;
		}
	}

	static class ViewHolder {
		TextView mainord;
		TextView psmoney;
		TextView typename;	//类型名称
		TextView addtime;	//下单时间
		TextView wpname;	//商品名称
		TextView sendaddr;	//送货地址
		
	}

}
